// 导入 Vue Router 的创建函数和历史模式
import { createRouter, createWebHistory } from 'vue-router';
// 导入视图组件
import AppLogin from '@/views/AppLogin.vue';
import AppRegister from '@/views/AppRegister.vue';
import ServiceAppointmentAndMatching from '@/views/ServiceAppointmentAndMatching.vue';

// 定义路由配置
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'AppLogin',
    component: AppLogin
  },
  {
    path: '/register',
    name: 'AppRegister',
    component: AppRegister
  },
  {
    path: '/service-appointment-and-matching',
    name: 'ServiceAppointmentAndMatching',
    component: ServiceAppointmentAndMatching
  },
  {
    path: '/health-management',
    name: 'HealthManagement',
    component: () => import('@/views/HealthManagement.vue')
  },
  {
    path: '/social-activities',
    name: 'SocialActivities',
    component: () => import('@/views/SocialActivities.vue')
  },
  {
    path: '/time-bank',
    name: 'TimeBank',
    component: () => import('@/views/TimeBank.vue')
  },
  {
    path: '/my-services',
    name: 'MyServices',
    component: () => import('@/views/MyServices.vue')
  }
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局导航守卫，确保未登录用户无法访问其他页面
router.beforeEach((to, from, next) => {
  // 如果是访问登录或注册页面，直接通过
  if (to.path === '/login' || to.path === '/register') {
    return next();
  }
  
  // 检查用户是否已登录
  const loggedIn = localStorage.getItem('user');
  if (!loggedIn) {
    return next('/login');
  }
  
  next();
});

// 导出路由实例
export default router;